var express = require('express')
var router = express.Router()
const querySql = require('../db/index')
const jwt = require('jsonwebtoken')
const { PRIVATE_KEY, EXPIRESD } = require('../utils/contant')
const { upload } = require('../utils/index')
const Mock = require('mockjs')
const sqlFn = require('../db/index2')

//登录接口
router.post('/user/login', async (req, res, next) => {
  let { username, password } = req.body
  try {
    let user = await querySql('select * from user where username = ?', [username])
    if (!user || user.length === 0) {
      res.send({ code: -1, msg: '该账户不存在' })
    } else {
      let result = await querySql('select * from user where username = ? and password = ?', [username, password])
      if (!result || result.length === 0) {
        res.send({ code: -1, msg: '账号或密码不正确' })
      } else {
        let token = jwt.sign({ username }, PRIVATE_KEY, { expiresIn: EXPIRESD })
        res.send({ code: 0, msg: '登录成功', token: token })
      }
    }
  } catch (err) {
    console.log(err)
    next(err)
  }
})

/* 注册接口 */
router.post('/user/register', async (req, res, next) => {
  let { username, password } = req.body
  try {
    let user = await querySql('select * from user where username = ?', [username])
    if (!user || user.length === 0) {
      await querySql('insert into user(username,password) value(?,?)', [username, password])
      res.send({ code: 0, msg: '注册成功' })
    } else {
      res.send({ code: -1, msg: '该账号已注册' })
    }
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//头像上传接口
router.post('/upload', upload.single('file'), async (req, res, next) => {
  // console.log(req.file)
  let imgPath = req.file.path.split('public')[1].replaceAll('\\', '/')
  let imgUrl = 'http://127.0.0.1:3000' + imgPath
  res.send({ code: 0, msg: '上传成功', data: imgUrl })
})

// 商品搜索
router.get('/search', async (req, res) => {
  var search = req.query.search
  const sql = "select * from goods where  concat(`title`,`sellPoint`,`descs`) like '%" + search + "%'"
  let result = await querySql(sql)
  res.send({ code: 0, msg: '搜索成功', data: result })
})

//获取商品
router.get('/getProductData', async (req, res) => {
  const sqlStr = `SELECT * FROM goods`
  let sqlLen = 'select count(*) as count from goods'
  sqlLen = await querySql(sqlLen)
  sqlFn(sqlStr, (error, results, fields) => {
    if (error) {
      res.json({ err_code: 0, message: '获取失败' })
    } else {
      console.log('length', sqlLen[0].count)

      results = JSON.parse(JSON.stringify(results))
      res.json({ success_code: 200, data: results, total: sqlLen[0].count })
    }
  })
})

//商品分页查询
router.post('/page', async (req, res) => {
  let pageNo = Number(req.body.page) || 1
  let pageCount = Number(req.body.pageSize) || 4
  let pageSize = pageCount
  let page = (pageNo - 1) * pageCount
  // console.log(page,pageSize);
  let sqlStr = `select * from goods order by id desc limit ${page},${pageSize}`
  sqlFn(sqlStr, (error, results, fields) => {
    if (error) {
      console.log(error)
      res.json({ err_code: 0, message: '获取分页数据失败' })
    } else {
      res.json({ success_code: 200, message: '获取分页数据成功', data: results })
    }
  })
})

// 删除商品
router.post('/goods/delete', async (req, res, next) => {
  let { id } = req.body

  try {
    let sql = 'delete from goods where id = ?'
    let result = await querySql(sql, [id])
    console.log(result)
    res.send({ code: 0, msg: '删除成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 商品添加
router.post('/goods/add', async (req, res, next) => {
  let { title, price, num, date, image, sellPoint, descs } = req.body
  try {
    await querySql('insert into goods( title, price, num, date, image, sellPoint, descs) values(?,?,?,?, ?, ?, ?)', [title, price, num, date, image, sellPoint, descs])
    res.send({ code: 0, msg: '新增成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 更新商品
router.post('/goods/edit', async (req, res, next) => {
  let { id, title, price, num, date, image, sellPoint, descs } = req.body
  try {
    await querySql('update goods set title = ?,price = ?, num=?, date=?, image=?, sellPoint=?, descs=? where id = ?', [title, price, num, date, image, sellPoint, descs, id])
    res.send({ code: 0, msg: '修改成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//获取订单
router.get('/order/getOrderList', async (req, res, next) => {
  try {
    let sql = `select id , order_name, order_weight,num, price , status,address, is_send, order_time from orders`
    let result = await querySql(sql)
    let sqlLen = 'select count(*) as count from orders'
    sqlLen = await querySql(sqlLen)
    res.send({ code: 0, msg: '获取成功', data: result, total: sqlLen[0].count })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//订单分页查询
router.post('/order/page', async (req, res) => {
  let pageNo = Number(req.body.page) || 1
  let pageCount = Number(req.body.pageSize) || 4
  let pageSize = pageCount
  let page = (pageNo - 1) * pageCount
  let sqlStr = `select * from orders order by id desc limit ${page},${pageSize}`
  sqlFn(sqlStr, (error, results, fields) => {
    if (error) {
      console.log(error)
      res.json({ err_code: 0, message: '获取分页数据失败' })
    } else {
      res.json({ success_code: 200, message: '获取分页数据成功', data: results })
    }
  })
})

// 订单搜索
router.get('/order/search', async (req, res) => {
  var search = req.query.search
  const sql = "select * from orders where  concat(`order_name`,`order_weight`,`num`,`price`,`address`,`is_send`) like '%" + search + "%'"
  let result = await querySql(sql)
  res.send({ code: 0, msg: '搜索成功', data: result })
})

// 通知
router.get('/notice', async (req, res, next) => {
  try {
    let sql = `select id ,title, content, remark  from publish`
    let result = await querySql(sql)
    res.send({ code: 0, msg: '获取成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 商品添加
router.post('/publish/add', async (req, res, next) => {
  let { content, remark, title } = req.body
  try {
    await querySql('INSERT INTO publish(content,remark,title) VALUES (?,?,?)', [content, remark, title])
    res.send({ code: 0, msg: '新增成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 删除商品
router.post('/publish/delete', async (req, res, next) => {
  let { id } = req.body
  try {
    let sql = 'delete from publish where id = ?'
    let result = await querySql(sql, [id])
    console.log(result)
    res.send({ code: 0, msg: '删除成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 获取用户所有数据
router.get('/user', async (req, res, next) => {
  try {
    let sql = `select id ,username, password, mg_state, head_img , email, phone  from user `
    let result = await querySql(sql)
    let sqlLen = 'select count(*) as count from user'
    sqlLen = await querySql(sqlLen)
    res.send({ code: 0, msg: '获取成功', data: result, total: sqlLen[0].count })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//用户分页查询
router.post('/user/page', async (req, res) => {
  let pageNo = Number(req.body.page) || 1
  let pageCount = Number(req.body.pageSize) || 4
  let pageSize = pageCount
  let page = (pageNo - 1) * pageCount
  let sqlStr = `select * from user order by id desc limit ${page},${pageSize}`
  sqlFn(sqlStr, (error, results, fields) => {
    if (error) {
      console.log(error)
      res.json({ err_code: 0, message: '获取分页数据失败' })
    } else {
      res.json({ success_code: 200, message: '获取分页数据成功', data: results })
    }
  })
})

// 用户新增
router.post('/user/add', async (req, res, next) => {
  let { username, password, head_img, email, phone } = req.body
  try {
    await querySql('insert into user( username, password, head_img, email, phone) values(?,?,?,?, ?)', [username, password, head_img, email, phone])
    res.send({ code: 0, msg: '新增成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 删除用户
router.post('/user/delete', async (req, res, next) => {
  let { id } = req.body
  try {
    let sql = 'delete from user where id = ?'
    let result = await querySql(sql, [id])
    console.log(result)
    res.send({ code: 0, msg: '删除成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 用户编辑
router.post('/user/edit', async (req, res, next) => {
  let { id, username, password, head_img, email, phone } = req.body
  try {
    await querySql('update user set username = ?,password = ?,head_img=?, email=?, phone=? where id = ?', [id, username, password, head_img, email, phone])
    res.send({ code: 0, msg: '修改成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 用户搜索
router.get('/user/search', async (req, res) => {
  var search = req.query.search
  const sql = "select * from user where  concat(`username`,`email`,`phone`) like '%" + search + "%'"
  let result = await querySql(sql)
  res.send({ code: 0, msg: '搜索成功', data: result })
})

router.get('/getEcharts', (req, res) => {
  let List = []
  for (let i = 0; i < 7; i++) {
    List.push(
      Mock.mock({
        vue: Mock.Random.float(100, 8000, 0, 2),
        wechat: Mock.Random.float(100, 8000, 0, 2),
        ES6: Mock.Random.float(100, 8000, 0, 2),
        Redis: Mock.Random.float(100, 8000, 0, 2),
        React: Mock.Random.float(100, 8000, 0, 2),
        springboot: Mock.Random.float(100, 8000, 0, 2)
      })
    )
  }
  let lists = {
    // 饼图
    videoData: [
      {
        name: 'springboot',
        value: Mock.Random.float(1000, 10000, 0, 2)
      },
      {
        name: 'vue',
        value: Mock.Random.float(1000, 10000, 0, 2)
      },
      {
        name: '小程序',
        value: Mock.Random.float(1000, 10000, 0, 2)
      },
      {
        name: 'ES6',
        value: Mock.Random.float(1000, 10000, 0, 2)
      },
      {
        name: 'Redis',
        value: Mock.Random.float(1000, 10000, 0, 2)
      },
      {
        name: 'React',
        value: Mock.Random.float(1000, 10000, 0, 2)
      }
    ],
    // 柱状图
    userData: [
      {
        date: '周一',
        new: Mock.Random.integer(1, 100),
        active: Mock.Random.integer(100, 1000)
      },
      {
        date: '周二',
        new: Mock.Random.integer(1, 100),
        active: Mock.Random.integer(100, 1000)
      },
      {
        date: '周三',
        new: Mock.Random.integer(1, 100),
        active: Mock.Random.integer(100, 1000)
      },
      {
        date: '周四',
        new: Mock.Random.integer(1, 100),
        active: Mock.Random.integer(100, 1000)
      },
      {
        date: '周五',
        new: Mock.Random.integer(1, 100),
        active: Mock.Random.integer(100, 1000)
      },
      {
        date: '周六',
        new: Mock.Random.integer(1, 100),
        active: Mock.Random.integer(100, 1000)
      },
      {
        date: '周日',
        new: Mock.Random.integer(1, 100),
        active: Mock.Random.integer(100, 1000)
      }
    ],
    // 折线图
    orderData: {
      date: ['20191001', '20191002', '20191003', '20191004', '20191005', '20191006', '20191007'],
      data: List
    },
    tableData: [
      {
        name: 'ES6',
        todayBuy: Mock.Random.float(100, 1000, 0, 2),
        monthBuy: Mock.Random.float(3000, 5000, 0, 2),
        totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
      },
      {
        name: '小程序',
        todayBuy: Mock.Random.float(100, 1000, 0, 2),
        monthBuy: Mock.Random.float(3000, 5000, 0, 2),
        totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
      },
      {
        name: 'Vue',
        todayBuy: Mock.Random.float(100, 1000, 0, 2),
        monthBuy: Mock.Random.float(3000, 5000, 0, 2),
        totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
      },
      {
        name: 'springboot',
        todayBuy: Mock.Random.float(100, 1000, 0, 2),
        monthBuy: Mock.Random.float(3000, 5000, 0, 2),
        totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
      },
      {
        name: 'React',
        todayBuy: Mock.Random.float(100, 1000, 0, 2),
        monthBuy: Mock.Random.float(3000, 5000, 0, 2),
        totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
      },
      {
        name: 'Redis',
        todayBuy: Mock.Random.float(100, 1000, 0, 2),
        monthBuy: Mock.Random.float(3000, 5000, 0, 2),
        totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
      }
    ]
  }
  res.send({ code: 0, msg: '获取列表成功', data: lists })
})

router.get('/getMockPersonal', (req, res) => {
  let List = []
  for (let i = 0; i < 10; i++) {
    List.push(
      Mock.mock({
        date: Mock.Random.date(),
        name: Mock.Random.first(),
        city: Mock.Random.county(true)
      })
    )
  }
  res.send({ code: 0, msg: '获取列表成功', data: List })
})

// 获取轮播图图片
router.get('/carousel', async (req, res, next) => {
  try {
    let sql = `select id ,lb_img  from carousel`
    let result = await querySql(sql)
    res.send({ code: 0, msg: '获取成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 轮播图图片编辑
router.post('/carousel/edit', async (req, res, next) => {
  let { id, lb_img } = req.body
  try {
    await querySql('update carousel set lb_img = ? where id = ?', [lb_img, id])
    res.send({ code: 0, msg: '修改成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 获取head_img图片
router.post('/head_img', async (req, res, next) => {
  let { username } = req.body
  try {
    let result = await querySql('select head_img  from user where username = ?', [username])
    res.send({ code: 0, msg: '获取成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 修改head_img图片
router.post('/update/head_img', async (req, res, next) => {
  let { username, head_img } = req.body
  try {
    let result = await querySql('update user set head_img = ? where username = ?', [head_img, username])
    res.send({ code: 0, msg: '修改成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//获取前8条商品
router.get('/limit/getProductData', async (req, res, next) => {
  try {
    let sql = `select *  from goods limit 8`
    let result = await querySql(sql)
    res.send({ code: 0, msg: '获取成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 获取标题商品的信息
router.post('/detail', async (req, res, next) => {
  let { id } = req.body
  try {
    let result = await querySql('select * from goods where id = ?', [id])
    res.send({ code: 0, msg: '获取数据成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//发表评论接口
router.post('/comment', async (req, res, next) => {
  let { content, article_id, username } = req.body
  console.log(username)
  try {
    let userSql = 'select id,head_img from user where username = ?'
    let user = await querySql(userSql, [username])
    console.log(user)
    let { id: user_id, head_img } = user[0]
    let sql = 'insert into comment(user_id,article_id,cm_content,head_img,create_time) values(?,?,?,?,NOW())'
    let result = await querySql(sql, [user_id, article_id, content, head_img])
    res.send({ code: 0, msg: '发表成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//评论列表接口
router.get('/CommentList', async (req, res, next) => {
  let { article_id } = req.query
  try {
    let sql = 'select id,head_img,cm_content,DATE_FORMAT(create_time,"%Y-%m-%d %H:%i:%s") AS create_time from comment  where article_id = ? order by id desc'
    let result = await querySql(sql, [article_id])
    res.send({ code: 0, msg: '成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//获取后10条商品
router.get('/limit8/getMoreData', async (req, res, next) => {
  try {
    let sql = `select *  from goods order by id desc limit 20`
    let result = await querySql(sql)
    res.send({ code: 0, msg: '获取成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//获取后4条商品数据作为轮播图数据
router.get('/limit4/getCarouselData', async (req, res, next) => {
  try {
    let sql = `select *  from goods order by id desc limit 4`
    let result = await querySql(sql)
    res.send({ code: 0, msg: '获取成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//获取5,6,7条商品
router.get('/limit3/getMoreData', async (req, res, next) => {
  try {
    let sql = `select *  from goods limit 4,3`
    let result = await querySql(sql)
    res.send({ code: 0, msg: '获取成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 添加购物车
router.post('/add_car', async (req, res, next) => {
  let { id, times, count } = req.body
  try {
    let sql = 'INSERT INTO car(list_id,times,count) VALUES (?,?,?)'
    let result = await querySql(sql, [id, times, count])
    res.send({ code: 0, msg: '添加成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//查询喜欢/收藏/购物车
router.get('/get_car', async (req, res, next) => {
  try {
    let sql = 'SELECT a.status, a.id ,a.list_id,a.times,a.count,b.sellPoint,b.image,b.price FROM car  a  LEFT JOIN goods b ON a.list_id=b.id  ORDER BY a.id DESC'
    let result = await querySql(sql)
    res.send({ code: 0, msg: '获取列表成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

//删除喜欢/收藏/购物车
router.post('/del_car', async (req, res, next) => {
  let { id } = req.body
  try {
    let sql = 'DELETE FROM car WHERE id=?'
    let result = await querySql(sql, id)
    res.send({ code: 0, msg: '删除成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 获取个人中心信息
router.post('/person/message', async (req, res, next) => {
  let { username } = req.body
  try {
    let sql = `select username, password, head_img ,email, phone from user where username = ?`
    let result = await querySql(sql, username)
    res.send({ code: 0, msg: '获取成功', data: result })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 修改个人中心信息
router.post('/update/person', async (req, res, next) => {
  let { username, password, head_img, email, phone, user } = req.body
  try {
    let result = await querySql('update user set username=?, password=?, head_img = ?, email=? , phone = ?where username = ?', [username, password, head_img, email, phone, user])
    res.send({ code: 0, msg: '修改成功', data: null })
  } catch (e) {
    console.log(e)
    next(e)
  }
})

// 用户用户名搜索
// router.get('/user/search', async (req, res) => {
//   var search = req.query.search
//   const sql = "select * from user where  concat(`username`,`email`,`phone`) like '%" + search + "%'"
//   let result = await querySql(sql)
//   res.send({ code: 0, msg: '搜索成功', data: result })
// })
router.get('/user/search1', async (req, res) => {
  var search = req.query.search
  const sql = "select * from user where username like '%" + search + "%'"
  let result = await querySql(sql)
  res.send({ code: 0, msg: '搜索成功', data: result })
})

router.get('/user/search2', async (req, res) => {
  var search = req.query.search
  const sql = "select * from user where email like '%" + search + "%'"
  let result = await querySql(sql)
  res.send({ code: 0, msg: '搜索成功', data: result })
})

router.get('/user/search3', async (req, res) => {
  var search = req.query.search
  const sql = "select * from user where phone like '%" + search + "%'"
  let result = await querySql(sql)
  res.send({ code: 0, msg: '搜索成功', data: result })
})


module.exports = router
